package com.sr.controller.api;

import com.sr.annotation.ApiAuth;
import com.sr.constant.Constant;
import com.sr.controller.BaseController;
import com.sr.enums.ResponseCode;
import com.sr.exception.Assert;
import com.sr.exception.BusinessException;
import com.sr.service.ILoginService;
import com.sr.util.R;
import com.sr.vo.req.LoginVo;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaochi
 * @date 2022/5/1 11:04
 * @desc LoginControllerApi
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping(Constant.Api.WEB_PREFIX)
@RequiredArgsConstructor(onConstructor = @__)
public class LoginControllerApi extends BaseController {

    private final ILoginService loginService;

    /**
     * 获取验证码
     * @return
     */
    @ApiOperation(value = "获取验证码",notes = "获取验证码接口，返回Base64")
    @GetMapping("/captcha")
    public R<Map<String,String>> captcha(){
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 5);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        this.getRequest().getSession(true).setAttribute(Constant.CAPTCHA_CODE,captcha.text());
        Map<String,String> map = new HashMap<>();
        map.put("code",captcha.toBase64());
        return R.ok(map);
    }

    /**
     * 登录
     * @param loginVo
     * @return
     */
    @ApiOperation(value = "登录接口",notes = "登录接口")
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody @Valid LoginVo loginVo){
        String code = (String)this.getRequest().getSession().getAttribute(Constant.CAPTCHA_CODE);
        Assert.assertNotNull(code,new BusinessException(ResponseCode.SYSTEM_VERIFY_CODE_EXPIRED));
        Assert.isTure(code.equalsIgnoreCase(loginVo.getCode()),new BusinessException(ResponseCode.SYSTEM_VERIFY_CODE_ERROR));
        return R.ok(loginService.login(loginVo));
    }

    /**
     * 退出登录
     * @return
     */
    @ApiOperation(value = "退出登录接口",notes = "退出登录接口")
    @ApiAuth
    @GetMapping("/logout")
    public R<String> logout(){
        String token = this.getToken();
        loginService.logout(token,this.getUserId(token));
        return R.ok();
    }
}
